<template>
  <div>
    <el-card>
      <div class="border">
        <span style="font-size: 17px;font-weight: bold">发布共享文档</span>
      </div>
      <div style="padding:10px 150px;margin-top:10px">
        <el-form
          ref="form"
          :rules="rules"
          :model="formInfo"
          label-width="120px"
          v-loading="loading1"
        >
          <el-form-item label="共享标题：" prop="title">
            <el-input
              v-model="formInfo.title"
              placeholder="请输入标题"
              class="input_content"
            ></el-input>
          </el-form-item>
          <el-form-item label="文档类型：" prop="categoryId">
            <el-select
              class="mr5"
              v-model="formInfo.categoryId"
              placeholder="请选择文档类型"
              @change="selectWorkName"
              style="width: 300px"
            >
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="接收人员：" prop="acceptUsers">
            <user-select
              :class="'input_content'"
              :isMulSelect="true"
              placeholder="请选择接收人员"
              v-model="formInfo.acceptUsers"
            ></user-select>
          </el-form-item>
          <el-form-item
            v-if="oriList.length > 1"
            label="发送部门："
            prop="organizeId"
          >
            <el-select
              class="mr5"
              v-model="formInfo.organizeId"
              placeholder="请选择部门"
              @change="selectWorkName1"
              style="width: 300px"
            >
              <el-option
                v-for="item in oriList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="短信通知：" prop="needSms">
            <template>
              <el-switch
                v-model="formInfo.needSms"
                active-color="#13ce66"
                active-text="开启"
                inactive-text="关闭"
                :active-value="true"
                :inactive-value="false"
              ></el-switch>
            </template>
          </el-form-item>
          <el-form-item label="选择文件：" prop="files">
            <el-upload
              class="upload-demo"
              :action="imgHead"
              :headers="head"
              :accept="accept"
              :on-success="handleSuccess"
              :on-preview="handlePreview"
              :on-error="handleError"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
              :limit="10"
              :on-exceed="handleExceed"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">{{acceptTitle}}</div>
            </el-upload>
          </el-form-item>
          <el-form-item style="padding-top: 20px;display: flex">
            <el-button
              style="float:left;margin-right: 10px"
              :loading="loading"
              type="primary"
              @click="release"
            >
              发布
            </el-button>
<!--            <user-select-->
<!--              style="display: inline-block;"-->
<!--              :disabled="-->
<!--                !this.formInfo.title ||-->
<!--                  !this.formInfo.categoryId ||-->
<!--                  !this.formInfo.acceptUsers ||-->
<!--                  !this.formInfo.files ||-->
<!--                  (oriList.length > 1 ? !this.formInfo.organizeId : false)-->
<!--              "-->
<!--              :func-submit="userSubmit"-->
<!--              :loading="loading1"-->
<!--              :btnLabel="'发送审核'"-->
<!--              :isHiddenInput="true"-->
<!--              @getUser="getUser"-->
<!--            ></user-select>-->
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>
<script>
import userSelect from "@/components/user-select.vue";

export default {
  created() {
    this.getCategoryTree();
    this.getOri();
    this.getSettingByKey();
  },
  data() {
    return {
      acceptTitle:'',
      accept:"",
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        categoryId: [
          { required: true, message: "请输入文档类型", trigger: "blur" }
        ],
        acceptUsers: [
          { required: true, message: "请输入接收人员", trigger: "blur" }
        ],
        organizeId: [
          { required: true, message: "请输入部门", trigger: "blur" }
        ],
        files: [{ required: true, message: "请上传文件", trigger: "blur" }]
      },
      // 上传配置
      imgHead: window.api.sysUploadUrl + "?path=document",
      head: {
        userRole: "ADMIN",
        token: window.sessionStorage.getItem("token")
      },
      loading: false,
      loading1: false,
      categoryList: [], //文档类型列表
      oriList: [], //部门列表
      fileList: [], //el-upload默认
      //新增文档表单
      formInfo: {
        title: "", //标题
        categoryId: "", //文档类型id
        categoryName: "", //文档类型
        acceptUsers: "", //接收人员
        needSms: false, //是否通知
        organizeId: "", //部门id
        organizeName: "", //部门名称
        // files: [], //文件id
        files: "",
        fileCount: "", //文件数量
        status: "",
        auditUserId: "",
        auditUserName: "",
        module: "DOCUMENT"
      }
    };
  },
  methods: {
    getSettingByKey() {
      this.API.getModuleSettingByKey({key: 'DOCUMENT'}).then(res => {
        this.accept = '';
        if (res.data.fileTypes) {
          this.imgHead = window.api.sysUploadUrl + `?path=document&fileTypes=${res.data.fileTypes}`
          let arr = res.data.fileTypes.split(',');
          let nextArr = arr.map(item => {
            return "." + item
          })
          this.accept = nextArr.join(',')
        }
        this.acceptTitle = res.data.description ? res.data.description : ''
      })
    },
    handleError(err, file, fileList) {
      this.$notify.error({
        title: "错误",
        dangerouslyUseHTMLString: true,
        duration: 2000,
        message: `<p style="display: block;width: 260px; word-wrap: break-word">${
          JSON.parse(err.message).message
        }</p>`
      });
    },
    //获取当前用户下部门
    getOri() {
      this.API.getOrganizeListByUserId().then(ret => {
        this.oriList = ret.data;
        this.formInfo.organizeId = this.oriList[0].id;
        this.formInfo.organizeName = this.oriList[0].name;
      });
    },
    //获取部门名称
    selectWorkName1(val) {
      let obj = this.oriList.find(item => item.id === val);
      this.formInfo.organizeName = obj.name;
    },
    //获取分类名称
    selectWorkName(id) {
      let obj = this.categoryList.find(item => item.id === id);
      this.formInfo.categoryName = obj.name;
    },
    //上传成功
    handleSuccess(res, file, fileList) {
      this.formInfo.files = "";
      let ids = [];
      fileList.map(item => {
        if (item.response && item.response.id) {
          ids.push(item.response.id);
        }
      });
      this.formInfo.files = ids.join(",");
      this.formInfo.fileCount = fileList.length;
    },
    handleRemove(file, fileList) {
      let arr = this.formInfo.files.split(",");
      let index = arr.indexOf(file.response.id);
      arr.splice(index, 1);
      this.formInfo.files = arr.join(",");
    },
    handlePreview(file) {
      console.log(file.response.id);
      this.openTabPage(
        window.api.preFile +
          "?url=" +
          window.api.secretFilePreview +
          file.response.id +
          "?token=" +
          window.sessionStorage.getItem("token")
      );
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 10 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    getUser(val) {
      this.formInfo.auditUserId = val.origId;
      this.formInfo.auditUserName = val.userNames;
    },
    userSubmit() {
      if (!this.formInfo.auditUserId) {
        this.$message.error("请至少选择一个人员");
        return;
      }
      // this.formInfo.organizeId =
      //   this.oriList.length > 1 ? this.formInfo.organizeId : this.oriList[0].id;
      // this.formInfo.organizeName =
      //   this.oriList.length > 1
      //     ? this.formInfo.organizeName
      //     : this.oriList[0].name;
      this.formInfo.status = "WAIT_HANDLE";
      let tem = { body: this.formInfo };
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading1 = true;
          this.API.addOrUpdateDocument(tem).then(ret => {
            this.success("发布成功");
            this.$router.push({ name: "myRelease" });
            this.fileList = [];
            this.loading1 = false;
          });
        }
      });
    },
    //发布文档
    release() {
      // this.formInfo.organizeId =
      //   this.oriList.length > 1 ? this.formInfo.organizeId : this.oriList[0].id;
      // this.formInfo.organizeName =
      //   this.oriList.length > 1
      //     ? this.formInfo.organizeName
      //     : this.oriList[0].name;
      this.formInfo.status = "COMPLETE";
      let tem = { body: this.formInfo };
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true;
          this.API.addOrUpdateDocument(tem).then(ret => {
            this.success("发布成功");
            this.$router.push({ name: "myRelease" });
            this.fileList = [];
            this.loading = false;
          });
        }
      });
    },
    //获取文档类型
    getCategoryTree() {
      this.API.getCategoryTree({ type: "DOCUMENT" }).then(res => {
        this.categoryList = res.data;
        this.formInfo.categoryId = this.categoryList[0].id;
        this.formInfo.categoryName = this.categoryList[0].name;
      });
    }
  },
  components: {
    userSelect
  }
};
</script>
<style scoped>
/deep/ .el-card__body {
  padding: 0;
}

.border {
  padding: 19px 0 19px 20px;
  border-bottom: 1px solid rgba(224, 238, 249, 1);
}

.input_content {
  float: left;
  width: 500px;
  height: auto;
  margin-right: 150px;
  box-sizing: border-box;
  font-size: 14px;
  /*color: #666666;*/
  text-align: left;
}

/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #409eff;
  color: white;
}

[data-v-05e2a05e] /deep/ .el-input__inner {
  width: 430px;
}

/deep/ [data-v-05e2a05e] {
  float: left;
}
</style>
